package com.hoshiicloud.payment.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.payment.Payment;
import com.hoshiicloud.payment.param.PaymentQueryParam;
import com.hoshiicloud.payment.param.WeixinAddParam;
import com.hoshiicloud.payment.param.WeixinUpdateParam;
import com.hoshiicloud.payment.service.PaymentService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;

/**
 * <p>
 * 支付方式配置信息 控制器
 * </p>
 *
 * @author Mr.wu
 * @since 2019-05-13
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/payment/payment")
@Api(value = "支付方式配置", tags = {"支付方式配置"})
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    /**
    * @param param
    * @return com.hoshiicloud.common.rpc.Response
    * @description: 分页查询支付方式配置信息
    */
    @ApiOperation(value = "分页查询支付方式配置信息")
    @PostMapping("/query/page")
    public Response page(@Valid PaymentQueryParam param) {
        try {
            log.info("分页查询支付方式配置信息");
            QueryWrapper<Payment> queryWrapper = new QueryWrapper<Payment>();
            queryWrapper.eq(param.getId() != null, "id", param.getId());
            queryWrapper.eq(StringUtils.isNotBlank(param.getPayCode()), "pay_code", param.getPayCode());
            queryWrapper.eq(StringUtils.isNotBlank(param.getPayName()), "pay_name", param.getPayName());
            queryWrapper.eq(param.getEnabled() != null, "enabled", param.getEnabled());
            queryWrapper.eq(param.getIsCod() != null, "is_cod", param.getIsCod());
            queryWrapper.eq(param.getIsOnline() != null, "is_online", param.getIsOnline());
            IPage<Payment> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            queryWrapper.select(BeanUtils.getSqlSelect(Payment.class));
            return Response.data(paymentService.page(page, queryWrapper));
          } catch (ServiceException e) {
            return Response.failed(e.getError().getMsg());
          } catch (Exception e) {
            log.error("分页查询支付方式配置信息异常", e);
            return Response.failed("分页查询支付方式配置信息异常");
        }
    }
    /**
    * @param id
    * @return com.hoshiicloud.common.rpc.Response
    * @description: 根据id查询支付方式配置信息
    */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询支付方式配置信息")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response queryById(@PathVariable("id") Long id) {
        return Response.data(paymentService.getById(id));
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 新增
     */
    @PostMapping("/save/weixin")
    @ApiOperation(value = "新增微信支付配置")
    @ApiImplicitParams(
            @ApiImplicitParam(value = "证书文件,使用退款功能需要证书",name = "file",required = false,dataType = "MultipartFile",paramType = "formData")
    )
    public Response saveWeixin(@Valid WeixinAddParam param, MultipartFile file) {
        try {
            //如果文件不为空，上传证书文件，并保存objectKey到cert字段

            //由于最后保存时转换为json字符串,此处先取出配置再转换类型
            Payment data = BeanUtils.covertType(param, Payment.class);
            data.setPayConfig(param.configToJSONString());
            if(file!=null){
                return paymentService.saveByCert(data,file);
            }
            else{
                return Response.data(paymentService.save(data));
            }
        } catch (ServiceException e) {
            log.error("新增支付方式配置信息异常", e);
            return Response.failed(e.getError().getMsg());
        }catch (Exception e) {
            log.error("新增支付方式配置信息异常", e);
            return Response.failed(e.getMessage());
        }
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 修改支付方式配置信息
     */
    @PostMapping("/update/weixin")
    @ApiOperation(value = "修改微信支付配置")
    @ApiImplicitParams(
            @ApiImplicitParam(value = "证书文件,使用退款功能需要证书",name = "file",required = false,dataType = "MultipartFile",paramType = "formData")
    )
    public Response updateWeixin(@Valid WeixinUpdateParam param,MultipartFile file) {
        try {
            /**
             * 如果文件不为空，上传证书文件，并保存objectKey到cert字段
             * 如果cert字段不为空,则以cert字段为objectKey去更新文件,并清除缓存
             */

            Payment data = BeanUtils.covertType(param, Payment.class);
            data.setPayConfig(param.configToJSONString());
            if(file!=null){
                return paymentService.updateByCert(data,file);
            }
            else{
                return Response.data(paymentService.updateById(data));
            }

        }catch (ServiceException e) {
            log.error("修改支付方式配置信息异常", e);
            return Response.failed(e.getError().getMsg());
        }catch (Exception e) {
            log.error("修改支付方式配置信息异常", e);
            return Response.failed(e.getMessage());
        }
    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 删除支付方式配置信息
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除支付方式配置信息")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response delete(@PathVariable("id") Long id) {
        try {
            Payment data=paymentService.getById(id);
            if(data==null){
                log.error("删除支付方式配置信息异常，无法找到支付方式配置信息记录");
                return Response.failed("删除支付方式配置信息异常，无法找到支付方式配置信息记录");
            }
            paymentService.deleteById(data);
            return Response.success("删除支付方式配置信息成功");
        }catch (ServiceException e) {
            log.error("删除支付方式配置信息异常", e);
            return Response.failed(e.getError().getMsg());
        }catch (Exception e) {
            log.error("删除支付方式配置信息异常", e);
            return Response.failed(e.getMessage());
        }
    }

}
